<?php
 
$file =   $_FILES["file"];

$filename  =  $file["name"] ;//获取文件名
$error =  $file["error"] ;
$type = $file["type"] ;
if($error>0) {
    echo '文件上传失败';                                                    
}
else{
    //判断哪些文件可以上传   
    if($type=="image/jpeg"||$type=="image/png"||$type=="image/jpg"){
        //$filename = "QQ截图1221212.png"
        $filename_arr = explode(".",$filename);
        $filename =  time().'.'. $filename_arr[1];
        $path =  './public/2/'. $filename ;
        if(file_exists( $filename)){
            echo "文件已经上传过了";
        }
        else{
            //文件转存就可以
          if(move_uploaded_file($file["tmp_name"],$path)){
              echo "文件上传成功";
          }
          else{
              echo "文件上传失败";
          }
        }

    }
    else{
        echo "文件格式不正确";
    }
}

 

?>

<form enctype="multipart/form-data">
    <label for="avatar-upload" style="cursor:pointer;"><img src="./public/images/2017-08-12_230041.png" alt="" class="img-responsive"></label>
    <input type="file" name="files" style="display:none;" id="avatar-upload">
</form>

<script type="text/javascript">
    $(function() {
        document.getElementById("avatar-upload").change(function() {
              
            var formData = new FormData(document.get('form')[0]);

            //如何获取 文件选择框，选中的文件？？？？

            var select_file = $(':file')[0].files[0];
            formData.append('file', select_file); //我们已经准备好了，往后台传递文件了
            //异步传输  --- 页面不刷新了？？
            $.ajax({
                url: './handler/upload.php',
                type: 'POST',
                data: formData,
                cache: false, //上传文件必备几个属性
                processData: false,
                contentType: false,
                success: function(data) {
                    // $('.img-responsive').attr('src', data);
                }
            });


        })

    })
</script>